#include <gl/glew.h>
#include "Mesh.h"

#include <string>

Mesh::Mesh()
{
	mVBOId = -1;
	mIBOId = -1;
}

Mesh::Mesh(Vertex* pVertices, int pNbVertices, unsigned int *pIndices, unsigned int pNbIndices)
{
	mVBOId = -1;
	mIBOId = -1;
	setVertexBuffer(pVertices, pNbVertices, pIndices, pNbIndices);
}

void Mesh::setVertexBuffer(Vertex* pVertices, int pNbVertices, unsigned int *pIndices, unsigned int pNbIndices)
{
	glewInit();

	if(mVBOId != -1)
		glDeleteBuffers(1, (GLuint*)&mVBOId);
	if(mIBOId != -1)
		glDeleteBuffers(1, (GLuint*)&mIBOId);

	mNbIndices = pNbIndices;

	glGenBuffers(1, (GLuint*)&mVBOId);
	glGenBuffers(1, (GLuint*)&mIBOId);

	glBindBuffer(GL_ARRAY_BUFFER, mVBOId);
	glBufferData(GL_ARRAY_BUFFER, pNbVertices*sizeof(Vertex), &(pVertices[0].x), GL_STATIC_DRAW);

	//glBufferSubData(GL_ARRAY_BUFFER, 0, pNbVertices*sizeof(Vertex), &pVertices[0].x);

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIBOId);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, pNbIndices*sizeof(unsigned int), pIndices, GL_STATIC_DRAW);
	
	//glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, pNbIndices*sizeof(unsigned int), pIndices);
}

void Mesh::bindBuffers()
{
	glEnableClientState(GL_VERTEX_ARRAY);

	glBindBuffer(GL_ARRAY_BUFFER, mVBOId);

	//Position
	glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), NULL);
	//Normal
    /*glVertexAttribPointer(1, 3, GL_FLOAT, GL_TRUE, sizeof(Vertex), (void*)(4*sizeof(float)));
    glEnableVertexAttribArray(1);*/
	

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIBOId);
}

void Mesh::draw()
{
	glDrawElements(GL_TRIANGLES, mNbIndices, GL_UNSIGNED_INT, (void*)0);
}

void Mesh::loadFromFile(const char* pFile)
{

}